/**
 * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.guest.web;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.utils.excel.ExportExcel;
import com.thinkgem.jeesite.common.utils.excel.ImportExcel;
import com.thinkgem.jeesite.modules.guest.entity.UsAttendanceGuest;
import com.thinkgem.jeesite.modules.guest.service.UsAttendanceGuestService;
import com.thinkgem.jeesite.modules.warehouse.entity.BIWarehouseKpiData;

import org.apache.poi.ss.usermodel.Row;

/**
 * 美国外包Controller
 * 
 * @author hui.li
 * @version 2016-09-24
 */
@Controller
@RequestMapping(value = "${adminPath}/guest/usAttendanceGuest")
public class UsAttendanceGuestController extends BaseController {

	@Autowired
	private UsAttendanceGuestService usAttendanceGuestService;

	@ModelAttribute
	public UsAttendanceGuest get(@RequestParam(required = false) String id) {
		UsAttendanceGuest entity = null;
		if (StringUtils.isNotBlank(id)) {
			entity = usAttendanceGuestService.get(id);
		}
		if (entity == null) {
			entity = new UsAttendanceGuest();
		}
		return entity;
	}

	@RequiresPermissions("guest:usAttendanceGuest:view")
	@RequestMapping(value = { "list", "" })
	public String list(UsAttendanceGuest usAttendanceGuest,
			HttpServletRequest request, HttpServletResponse response,
			Model model) {
		Page<UsAttendanceGuest> page = usAttendanceGuestService.findPage(
				new Page<UsAttendanceGuest>(request, response),
				usAttendanceGuest);
		model.addAttribute("page", page);
		return "modules/guest/usAttendanceGuestList";
	}

	@RequiresPermissions("guest:usAttendanceGuest:view")
	@RequestMapping(value = "form")
	public String form(UsAttendanceGuest usAttendanceGuest, Model model) {
		model.addAttribute("usAttendanceGuest", usAttendanceGuest);
		return "modules/guest/usAttendanceGuestForm";
	}

	@RequiresPermissions("guest:usAttendanceGuest:edit")
	@RequestMapping(value = "save")
	public String save(UsAttendanceGuest usAttendanceGuest, Model model,
			RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, usAttendanceGuest)) {
			return form(usAttendanceGuest, model);
		}
		usAttendanceGuestService.save(usAttendanceGuest);
		addMessage(redirectAttributes, "保存美国外包成功");
		return "redirect:" + Global.getAdminPath()
				+ "/guest/usAttendanceGuest/?repage";
	}

	@RequiresPermissions("guest:usAttendanceGuest:edit")
	@RequestMapping(value = "delete")
	public String delete(UsAttendanceGuest usAttendanceGuest,
			RedirectAttributes redirectAttributes) {
		usAttendanceGuestService.delete(usAttendanceGuest);
		addMessage(redirectAttributes, "删除美国外包成功");
		return "redirect:" + Global.getAdminPath()
				+ "/guest/usAttendanceGuest/?repage";
	}

	/**
	 * 导入用户数据
	 * 
	 * @param file
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("guest:usAttendanceGuest:edit")
	@RequestMapping(value = "import", method = RequestMethod.POST)
	public String importFile(MultipartFile file,
			RedirectAttributes redirectAttributes) {
		if (Global.isDemoMode()) {
			addMessage(redirectAttributes, "演示模式，不允许操作！");
			return "redirect:" + adminPath
					+ "/guest/usAttendanceGuest/list?repage";
		}
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			UsAttendanceGuest guest = null;
			// 获取周一日期
			String strDate = null;
			List<UsAttendanceGuest> list = null;
			for (int i = ei.getDataRowNum(); i < ei.getLastDataRowNum(); i++) {

				try {
					Row row = ei.getRow(i);
					guest = new UsAttendanceGuest();

					if (0 == i || 1 == i || 2 == i) {
						continue;
					}
					if (3 == i) {
						for (int n = 0; n < ei.getLastCellNum(); n++) {
							Object val = ei.getCellValue(row, n);
							if (3 == n) {
								String str = String.valueOf(val);
								strDate = str.substring(12, 22);
								break;
							}
						}
						continue;
					}// end if

					list = new ArrayList<UsAttendanceGuest>();

					for (int j = 0; j < ei.getLastCellNum(); j++) {
						Object val = ei.getCellValue(row, j);
						if (0 == j) {
							if (null == val
									|| String.valueOf(val).length() <= 0) {
								break;
							}
						}

						switch (j) {
						case 0:
							guest.setEmployeeId(String.valueOf(val));
							break;
						case 1:
							guest.setLastName(String.valueOf(val));
							break;
						case 2:
							guest.setFirstName(String.valueOf(val));
							break;
						case 3:
							SimpleDateFormat sdf = new SimpleDateFormat(
									"mm/dd/yyyy");
							Date date = sdf.parse(String.valueOf(strDate));
							guest.setDate(date);
							guest.setDatevalue(String.valueOf(val));
							usAttendanceGuestService.save(guest);
							// list.add(guest);
							break;
						case 4:
							guest.setDate(getDate(strDate, "1"));
							guest.setDatevalue(String.valueOf(val));
							usAttendanceGuestService.save(guest);
							// list.add(guest);
							break;
						case 5:
							guest.setDate(getDate(strDate, "2"));
							guest.setDatevalue(String.valueOf(val));
							usAttendanceGuestService.save(guest);
							// list.add(guest);
							break;
						case 6:
							guest.setDate(getDate(strDate, "3"));
							guest.setDatevalue(String.valueOf(val));
							usAttendanceGuestService.save(guest);
							// list.add(guest);
							break;
						case 7:
							guest.setDate(getDate(strDate, "4"));
							guest.setDatevalue(String.valueOf(val));
							usAttendanceGuestService.save(guest);
							// list.add(guest);
							break;
						case 8:
							guest.setDate(getDate(strDate, "5"));
							guest.setDatevalue(String.valueOf(val));
							usAttendanceGuestService.save(guest);
							// list.add(guest);
							break;
						case 9:
							guest.setDate(getDate(strDate, "6"));
							guest.setDatevalue(String.valueOf(val));
							usAttendanceGuestService.save(guest);
							// list.add(guest);
							break;
						default:

							break;
						}// end switch
					}// end for

					// usAttendanceGuestService.batchInsert(list);
					successNum++;
					System.out.print("\n");
				} catch (Exception e) {
					// TODO: handle exception
					failureNum++;
				}
			}// end for
			if (failureNum > 0) {
				failureMsg.insert(0, "，失败 " + failureNum + " 条用户，导入信息如下：");
			}
			// addMessage(redirectAttributes, "已成功导入 " + successNum + " 条用户" +
			// failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入用户失败！失败信息：" + e.getMessage());
		}
		return "redirect:" + adminPath + "/guest/usAttendanceGuest/list?repage";
	}

	public Date getDate(String para, String next) {
		// System.out.println(para.substring(12, 22));
		Date returnDate = null;
		String strDate = null;
		Date date;
		try {
			date = (new SimpleDateFormat("mm/dd/yyyy")).parse(para);
			Calendar cal = Calendar.getInstance();
			cal.setTime(date);
			cal.add(Calendar.DATE, 1);
			strDate = (new SimpleDateFormat("mm/dd/yyyy"))
					.format(cal.getTime());
			SimpleDateFormat sdf = new SimpleDateFormat("mm/dd/yyyy");
			returnDate = sdf.parse(String.valueOf(strDate));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return returnDate;
	}

	/**
	 * 仓库BI报表
	 * 
	 * @param biWarehouseKpiData
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequiresPermissions("guest:usAttendanceGuest:view")
	@RequestMapping(value = { "biwrehouseKpiList", "" })
	public String findAllListBIWarehouseKpi(
			BIWarehouseKpiData biWarehouseKpiData, HttpServletRequest request,
			HttpServletResponse response, Model model) {
		Page<BIWarehouseKpiData> page = usAttendanceGuestService
				.findAllListBIWarehouseKpi(new Page<BIWarehouseKpiData>(
						request, response), biWarehouseKpiData);
		model.addAttribute("page", page);
		return "modules/guest/biwrehouseKpiList";
	}

	/**
	 * 导出考勤数据
	 * 
	 * @param user
	 * @param request
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("guest:usAttendanceGuest:view")
	@RequestMapping(value = "export", method = RequestMethod.POST)
	public String exportFile(HttpServletRequest request,
			HttpServletResponse response,
			RedirectAttributes redirectAttributes,
			BIWarehouseKpiData biWarehouseKpiData) {
		try {
			String fileName = "仓库KPI监控BI报表"
					+ DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
			Page<BIWarehouseKpiData> page = usAttendanceGuestService
					.findAllListBIWarehouseKpi(new Page<BIWarehouseKpiData>(
							request, response, -1), biWarehouseKpiData);
			new ExportExcel("仓库KPI监控BI报表", BIWarehouseKpiData.class)
					.setDataList(page.getList()).write(response, fileName)
					.dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出考勤失败！失败信息：" + e.getMessage());
		}
		return "redirect:" + Global.getAdminPath()
				+ "/guest/usAttendanceGuest/?repage";
	}
	
	/**
     * 导出考勤数据
     * @param user
     * @param request
     * @param response
     * @param redirectAttributes
     * @return
     */
    @RequiresPermissions("guest:usAttendanceGuest:view")
    @RequestMapping(value = "export2", method=RequestMethod.POST)
    public String exportFile( HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes,UsAttendanceGuest usAttendanceGuest) {
        try {
            String fileName = "美国外包考勤数据"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<UsAttendanceGuest> page = usAttendanceGuestService.findPage(new Page<UsAttendanceGuest>(request, response, -1), usAttendanceGuest); 
            new ExportExcel("美国外包考勤数据", UsAttendanceGuest.class).setDataList(page.getList()).write(response, fileName).dispose();
            return null;
        } catch (Exception e) {
            addMessage(redirectAttributes, "美国外包导出考勤失败！失败信息："+e.getMessage());
        }
        return "redirect:" + Global.getAdminPath() + "/guest/usAttendanceGuest/?repage";
    }

	
}
